﻿#include "component/MyApplication.h"
#include "controller/WindowManager.h"
#include "common/DarkStyle.h"
#include "common/RunGuard.h"
#include "common/Util.h"
#include "common/LogHandler.h"
// add by liq 13
//#include <QtSingleApplication>
#include "qtsingleapplication/src/qtsingleapplication.h"
//#include <QMessageBox>

int main(int argc, char *argv[])
{
//    qInstallMessageHandler(myMessageOutput);
//    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    // add by liq 14
    // 需要放在MAIN后执行，否则本工具窗口句柄还没获取到
    char* param_hwnd = NULL;
    if(argc > 1){
        param_hwnd = argv[1];
    }

    // modify by liq 13
//	MyApplication a(argc, argv);
    QtSingleApplication a("yfscreenshot-im", argc, argv);

    if(a.isRunning())//判断实例是否已经运行
    {
//        QMessageBox::warning(NULL, QString::fromLocal8Bit("提示！"), QString::fromLocal8Bit("该程序正在运行中！"));
        QString str = QString::fromLocal8Bit("该程序正在运行中！当前时间为：") + QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
        a.sendMessage(str, 10); //100ms后激活前个实例
        // add by liq 14
        // 本工具已启动时，IM再次启动时需要更新IM句柄以及返回本工具窗口句柄（再次启动时并不会将新的IM句柄拿到，原因未知，暂且在IM启动时杀掉原来的再重新启动）
        WindowManager::instance()->updateIMwinId(param_hwnd);
        return EXIT_SUCCESS;
    }
    qInstallMessageHandler(myMessageOutput);
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
//	a.setWindowIcon(QIcon(":/images/yfscreenshot.ico"));
    a.setWindowIcon(QIcon(":/images/yfx_exe.ico"));
    qDebug() << "=================yfscreenshot start===============";
	CDarkStyle::setFontFamily("Microsoft YaHei", false);
	CDarkStyle::assign();

	QApplication::setQuitOnLastWindowClosed(false);
	QObject::connect(&a, &QApplication::aboutToQuit, []{ WindowManager::instance()->destory(); });
    // 如果实例已经运行，则直接进行截图
//    QObject::connect(&a, &QtSingleApplication::messageReceived, []{ WindowManager::instance()->openWidget(WidgetID::SCREENSHOT); });
    // test by liq 13
    WindowManager::instance()->openWidget(WidgetID::MAIN);
//    WindowManager *w = WindowManager::instance();
//    w->openWidget(WidgetID::MAIN);

    // add by liq 14
    // 需要放在MAIN后执行，否则本工具窗口句柄还没获取到
    WindowManager::instance()->updateIMwinId(param_hwnd);

    // add by liq 10
    QFontDatabase::addApplicationFont((":/FontAwesome.ttf"));
    // TODO:直接启动截图（启动后立即关闭，实现预热功能，避免第一次启动耗时较长）
    WindowManager::instance()->openWidget(WidgetID::SCREENSHOT);
    WindowManager::instance()->closeWidget(WidgetID::SCREENSHOT);

    return a.exec();
}
